package com.tc.itfarm.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.google.common.collect.Maps;
import com.tc.itfarm.api.exception.BusinessException;
import com.tc.itfarm.api.model.SingleTableDao;
import com.tc.itfarm.dao.ArticleDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.api.model.PageList;
import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.api.util.PageQueryHelper;
import com.tc.itfarm.dao.CategoryDao;
import com.tc.itfarm.model.Category;
import com.tc.itfarm.model.CategoryCriteria;
import com.tc.itfarm.service.CategoryService;

@Service
public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryService {

	private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);
	@Resource
	private CategoryDao categoryDao;
	@Resource
	private ArticleDao articleDao;

	@Override
	public List<Category> selectAll(Short type) {
		CategoryCriteria criteria = new CategoryCriteria();
		criteria.or().andTypeEqualTo(type);
		return categoryDao.selectByCriteria(criteria);
	}

	@Override
	public PageList<Category> selectByPage(Page page) {
		CategoryCriteria criteria = new CategoryCriteria();
		return PageQueryHelper.queryPage(page, criteria, categoryDao, null);
	}

	@Override
	public void save(Category category) throws BusinessException {
		if (category.getRecordId() == null) {
			category.setCreateTime(DateUtils.now());
			// 查询是否名称重复
			CategoryCriteria criteria = new CategoryCriteria();
			criteria.or().andNameEqualTo(category.getName());
			int count = categoryDao.countByCriteria(criteria);
			if (count > 0) {
				throw BusinessException.create(logger, "分类名称已存在!");
			}
			categoryDao.insert(category);
		} else {
			categoryDao.updateById(category);
		}
	}

	@Override
	protected SingleTableDao getSingleDao() {
		return categoryDao;
	}

	@Override
	public Integer delete(Integer recordId) {
		// 该分类下的文章分类全部设为-1 表示未分类
		categoryDao.deleteById(recordId);
		Map<String, Object> map = Maps.newHashMap();
		map.put("desId", -1);
		map.put("sourceId", recordId);
		articleDao.changeCategory(map);
		return recordId;
	}

}
